﻿using System;
using System.Collections.Generic;

// Sending e-mail via Office365
using Microsoft.Exchange.WebServices.Auth;
using Microsoft.Exchange.WebServices.Autodiscover;
using Microsoft.Exchange.WebServices.Data;

namespace AIC_Notification
{
    public class EmailToOffice365
    {
        private ExchangeService service = null;

        public EmailToOffice365(string account, string password)
        {
            try
            {        
                // Create the binding.
                service = new ExchangeService();
            
                // Set the credentials for the on-premises server.
                service.Credentials = new WebCredentials(account, password);

                // Set the URL.
                service.AutodiscoverUrl(account, RedirectionCallback);
            }
            catch (Exception exception)
            {
                // handle exception
                Utility.Log("Account: " + account + " invalid.");
                throw;
            }
        }

        static bool RedirectionCallback(string url)
        {
            // Return true if the URL is an HTTPS URL.
            Utility.Log("Redirected to: " + url);
            return url.ToLower().StartsWith("https://");
        }

        public void SendHTML(IList<string> toRecipients, IList<string> ccRecipients, string subject, string htmlBody)
        {
            try
            {
                EmailMessage emailMessage = new EmailMessage(service);

                if (toRecipients != null)
                {
                    foreach (string toRecipient in toRecipients)
                        emailMessage.ToRecipients.Add(toRecipient);
                }
                if (ccRecipients != null)
                {
                    foreach (string ccRecipient in ccRecipients)
                        emailMessage.CcRecipients.Add(ccRecipient);
                }

                emailMessage.Subject = subject;
                emailMessage.Body = new MessageBody(BodyType.HTML, htmlBody);
                emailMessage.SendAndSaveCopy();
            }
            catch (AutodiscoverRemoteException exception)
            {
                // handle exception
                throw;
            }
        }
    }
}
